/*****************************************************************************
 * Copyright (c) 2010 -, Anders All rights reserved
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  Contact: Anders Uddenberg (anders.uddenberg@gmail.com)
 * 
 *
 ****************************************************************************/
package org.easypr.organizer.client.presenter;

import org.easypr.organizer.client.BackboneServiceAsync;
import org.easypr.organizer.client.MyUserService;
import org.easypr.organizer.client.MyUserServiceAsync;
import org.easypr.organizer.client.event.DisplayInformationEvent;
import org.easypr.organizer.shared.MyUser;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

// TODO: Auto-generated Javadoc
/**
 * The Class RegisterPresenter.
 */
public class RegisterPresenter implements Presenter {

	/**
	 * Define the interface the view needs to implement.
	 * 
	 * @author Anders
	 */
	public interface Display {
		
		/**
		 * Sets the data.
		 *
		 * @param email the new data
		 */
		void setData(String email);
		
		/**
		 * Clear form.
		 */
		void clearForm();
		/**
		 * As widget.
		 * 
		 * @return the widget
		 */
		Widget asWidget();
		
		/**
		 * Gets the name input.
		 *
		 * @return the name input
		 */
		TextBox getNameInput();
		
		/**
		 * Gets the email label.
		 *
		 * @return the email label
		 */
		Label getEmailLabel();
		
		/**
		 * Gets the cellphone input.
		 *
		 * @return the cellphone input
		 */
		TextBox getCellphoneInput();
		
		/**
		 * Gets the workphone input.
		 *
		 * @return the workphone input
		 */
		TextBox getWorkphoneInput();
		
		/**
		 * Gets the workplace input.
		 *
		 * @return the workplace input
		 */
		TextBox getWorkplaceInput();
		
		/**
		 * Gets the save button.
		 *
		 * @return the save button
		 */
		Button getSaveButton();
		
		/**
		 * Gets the logout link.
		 *
		 * @return the logout link
		 */
		Anchor getLogoutLink();
	
	}

	/** The event bus. */
	private final HandlerManager eventBus;
	
	/** The display. */
	private final Display display;
	
	/** The user. */
	private final MyUser user;
	
	/** The backbone rpc. */
	private BackboneServiceAsync backboneRPC;
	
	/** The user rpc. */
	private MyUserServiceAsync userRPC;

	
	/**
	 * Instantiates a new menu presenter.
	 *
	 * @param backboneRPC the backbone rpc
	 * @param eventBus the event bus
	 * @param view the view
	 * @param user the user
	 */
	public RegisterPresenter(BackboneServiceAsync backboneRPC, HandlerManager eventBus, Display view, MyUser user) {
		this.backboneRPC = backboneRPC;
		this.eventBus = eventBus;
		this.display = view;
		this.user = user;
	}
	

	/* (non-Javadoc)
	 * @see org.easypr.organizer.client.presenter.Presenter#go(com.google.gwt.user.client.ui.HasWidgets)
	 */
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		bind();
		updateContent();
	}
	
	/**
	 * Bind.
	 */
	private void bind() {
		
		display.getNameInput().addBlurHandler(new BlurHandler() {
			public void onBlur(BlurEvent event) {
				if(display.getNameInput().getText().trim().length() == 0) {
					//display.getNameInput().setText("Your name");
				}
			}
		});
		
		display.getNameInput().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if(display.getNameInput().getText().equals("Your name")) {
					display.getNameInput().setText("");
				}
			}
		});
		
		display.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				display.getSaveButton().setEnabled(false);
				
				final String name = (display.getNameInput().getText().trim().equals("Your name") ? 
						"" : display.getNameInput().getText().trim());
				
				String email = user.getEmail();
				//String cellphone = display.getCellphoneInput().getText().trim();
				//String workphone = display.getWorkphoneInput().getText().trim();
				String workplace = display.getWorkplaceInput().getText().trim();
				
				MyUser newUser = new MyUser(name, email, user.getNickname());
				newUser.setCellphone("");
				newUser.setWorkphone("");
				newUser.setWorkplace(workplace);
				AsyncCallback<MyUser> callback = new AsyncCallback<MyUser>() {
					public void onFailure(Throwable caught) {
						eventBus.fireEvent(new DisplayInformationEvent("Unable to proceed with the request!", DisplayInformationEvent.Severity.FAILURE));
					}
					public void onSuccess(MyUser user) {
						if(user != null) {
							// The user have successfully been registered
							Window.alert("User saved successfully");
							Window.Location.reload();
						} else {
							eventBus.fireEvent(new DisplayInformationEvent("Unable to register!", DisplayInformationEvent.Severity.FAILURE));
							// Something still went wrong
							// TODO: Fix event that show user save error
						}
					}
					
				};
				backboneRPC.saveUser(newUser, callback);
			}
			
		});
		
		
		display.getLogoutLink().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				GoogleLogout();
			}
		});
	}
	
	/**
	 * Google logout.
	 */
	private void GoogleLogout() {
		if(userRPC == null) {
			userRPC = GWT.create(MyUserService.class);
		}
		AsyncCallback<MyUser> callback = new AsyncCallback<MyUser>() {
			public void onFailure(Throwable caught) {
				eventBus.fireEvent(new DisplayInformationEvent("Unable to proceed with the request!", DisplayInformationEvent.Severity.FAILURE));
			}

			public void onSuccess(MyUser user) {
				if(user instanceof MyUser) {
					Window.Location.replace(user.getLogoutURL());
				} 
			}
		};
		userRPC.getUser(callback);
	}
	
	/**
	 * Main function to update the content of the container.
	 */
	public void updateContent() {
		display.setData(this.user.getEmail());
		display.clearForm();
	}
}

